package com.cloudptt.api.product.func.call.group.fsm.video.recv;

import com.cloudptt.api.comm.CauseCont;
import com.cloudptt.api.models.call.RtcpMsg;
import com.cloudptt.api.product.func.call.CallAttr;
import com.cloudptt.api.product.func.call.CallConst;
import com.cloudptt.api.product.func.call.group.fsm.video.IVideoSubState;
import com.cloudptt.api.product.log.Log;

import org.json.JSONException;
import org.json.JSONObject;


public class VideoRecvPermissionState implements IVideoSubState
{
	private VideoRecvAgent agent = null;
	private String jsonStr = null;

	public VideoRecvPermissionState(VideoRecvAgent agent)
	{
		this.agent = agent;
		Log.d(VideoRecvAgent.Log_Key, "currentState is VideoPermissionState");
		this.agent.opVideoRemoteWinShow(true);
	}
	public int doUserAction(int btnAction)
	{
		return CauseCont.OperateErr_NoAgent;
	}
	public int doUserAction(int btnAction,String jsonStr)
	{
		Log.d(VideoRecvAgent.Log_Key, "" + CallConst.stateTag(getState()) + " doUserAction btnAction = " + btnAction + " jsonStr = " + jsonStr);
		int result = CauseCont.OperateCheck_Suc;
		if(CallConst.BtnAction_Recv_End == btnAction)
		{
			try {
				this.jsonStr = jsonStr;
				JSONObject jsonObject = new JSONObject(jsonStr);
				String userId = jsonObject.getString(RtcpMsg.Key_UserId);
				long videoSsrc = jsonObject.getLong(RtcpMsg.Key_VideoSsrc);

				result = agent.sendRecv(CallAttr.RtcpMsg_Release, userId, 0, videoSsrc);
				agent.goToState(CallConst.VideoRecvState_PendingRelease);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	@Override
	public void receiveRtcpMsg(RtcpMsg msg) {
		// TODO Auto-generated method stub
		Log.d(VideoRecvAgent.Log_Key, "" + CallConst.stateTag(getState()) + " receiveRtcpMsg msg = " + msg);
		if(msg == null)
		{
			Log.d(VideoRecvAgent.Log_Key, "receiveRtcpMsg msg == null");
			return;
		}
		if(agent == null)
		{
			Log.d(VideoRecvAgent.Log_Key, "receiveRtcpMsg agent == null");
			return;
		}

		String title = msg.getTitle();
		if(title.equals(RtcpMsg.Title_MCV1_TRANSM_RECEP_NOTE))
		{
			String num = msg.getVideoTakenNum();//getValue(RtcpMsg.Key_McpttId);
			String jsonStr = msg.getTransInfoJson();
			Log.d(VideoRecvAgent.Log_Key, "receiveRtcpMsg num = " + num + " jsonStr = " + jsonStr);
			this.agent.notifyRecvUserInfo(num,jsonStr);
		}
		else if(title.equals(RtcpMsg.Title_MCV1_TRANSM_MEDIA_END_NOTE))
		{
			String num = msg.getVideoTakenNum();//getValue(RtcpMsg.Key_McpttId);
			String jsonStr = msg.getTransInfoJson();
			Log.d(VideoRecvAgent.Log_Key, "receiveRtcpMsg  num = " + num + " jsonStr = " + jsonStr);
			this.agent.notifyRecvEndUserInfo(num,jsonStr);
			this.agent.goToState(CallConst.VideoRecvState_NoPermission);
		}
//		else if(title.equals(RtcpMsg.Title_MCV1_GRANTED))
//		{
//		}
	}
	
	public void destory()
	{
		agent = null;
	}
	
	@Override
	public int getState() {
		// TODO Auto-generated method stub
		return CallConst.VideoRecvState_Permission;
	}
}
